//
//  THWKWebView.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//

#import "THWKWebView.h"
#import "THWebEventConst.h"

#import "THWKMessageHandlerManager.h"

static NSArray<NSString *> * defaultCookieNames = nil;
static NSArray<NSString *> * jsHandlerNames = nil;
static NSArray<NSString *> * defaultCookieWhiteNames = nil;

static BOOL hqHandleCookieForRequest = NO;
@interface THWKWebView()<WKUIDelegate,WKNavigationDelegate>

/**
 H5消息处理器
 */
@property (strong,nonatomic) id<THWKMessageHandlerProtocol> messageHandler;

@property (strong,nonatomic) WKNavigationAction * reloadAction;

@property (weak,nonatomic) WKUserContentController * kUserContentController;

@property (nonatomic) BOOL refreshScriptFlag;

@end

@implementation THWKWebView

- (NSURLRequest *)request
{
    NSURL * url = self.URL;
    if (url != nil)
    {
        return [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    }
    return nil;
}
+ (void)initialize
{
    if (@available(iOS 11.0, *))
    {
        hqHandleCookieForRequest = NO;
    }
    else
    {
        hqHandleCookieForRequest = YES;
    }
}

+ (WKProcessPool *)sharedProcessPool
{
    static WKProcessPool * kwProcessPool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        kwProcessPool = [WKProcessPool new];
    });
    return kwProcessPool;
}

+ (void)setDefaultCookieNameList:(NSArray<NSString *> *)defaultCookieNameList
{
    defaultCookieNames = defaultCookieNameList;
}

+ (NSArray<NSString *> *)defaultCookieNameList
{
    return defaultCookieNames;
}

+ (void)setDefaultCookieWhiteNameList:(NSArray<NSString *> *)defaultCookieWhiteNameList
{
    defaultCookieWhiteNames = defaultCookieWhiteNameList;
}

+ (NSArray<NSString *> *)defaultCookieWhiteNameList
{
    return defaultCookieWhiteNames;
}
+ (void)setJsHandlerNameList:(NSArray<NSString *> *)jsHandlerNameList
{
    jsHandlerNames = jsHandlerNameList;
}

+ (NSArray<NSString *> *)jsHandlerNameList
{
    return jsHandlerNames;
}
//设置默认cookie的脚本
+ (NSString *)cookieScript:(NSArray<NSString *> *)cookieList
{
    NSMutableString * scriptString = [NSMutableString new];
    for (NSHTTPCookie * cookie in [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies)
    {
        if ([cookieList containsObject:cookie.name])
        {
            NSString * cookieString = [NSString stringWithFormat:@"%@=%@;domain=%@;path=%@",cookie.name,cookie.value,cookie.domain,cookie.path?:@"/"];
            [scriptString appendFormat:@"document.cookie='%@';",cookieString];
        }
    }
    return scriptString;
}

//过滤掉不需要对比的cookie
+ (NSArray<NSHTTPCookie *> *)filterCookieList:(NSArray<NSHTTPCookie *> *)cookieList
{
    NSMutableArray<NSHTTPCookie *> * resultList = [NSMutableArray arrayWithCapacity:cookieList.count];
    for (NSHTTPCookie * cookie in cookieList)
    {
        if (cookie.isSessionOnly)
        {
            [resultList addObject:cookie];
        }
    }
    return resultList;
}

//校验白名单
+ (BOOL)checkCookieWhiteNameForRequest:(NSURLRequest *)request
{
    for (NSString *host in defaultCookieWhiteNames)
    {
        if ([request.URL.host containsString:host])
        {
            return YES;
        }
    }
    return NO;
}

//检查request的cookie是否和NSCookieStorage一致
+ (BOOL)validateCookieForRequest:(NSURLRequest *)request
{
    //不处理cookie或者不是主页面请求时 不用校验cookie
    if (!hqHandleCookieForRequest
        || ![request.mainDocumentURL isEqual:request.URL])
    {
        return YES;
    }
    //cookie在白名单里，不校验cookie
    if ([self checkCookieWhiteNameForRequest:request])
    {
        return YES;
    }
    
    if ([[request.URL scheme] hasPrefix:@"http"] && ![[request.URL absoluteString] containsString:@"cmd="])
    {
        NSString * cookieString = [request.allHTTPHeaderFields objectForKey:@"Cookie"];
        NSArray<NSHTTPCookie *> * cookieList = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
        cookieList = [self filterCookieList:cookieList];
        if (cookieList.count > 0)
        {
            if (cookieString.length == 0)
            {
                return NO;
            }
            else
            {
                NSArray<NSString *> * cookiePairList = [[cookieString stringByReplacingOccurrencesOfString:@" " withString:@""] componentsSeparatedByString:@";"];
                if (cookiePairList.count < cookieList.count)
                {
                    return NO;
                }
                else
                {
                    for (NSHTTPCookie * cookie in cookieList)
                    {
                        NSString * cookiePair = [NSString stringWithFormat:@"%@=%@",cookie.name,cookie.value];
                        if (![cookiePairList containsObject:cookiePair])
                        {
                            return NO;
                        }
                    }
                }
            }
        }
    }
    return YES;
}

//将请求返回的cookie设置到系统中
- (void)handleCookieFromResponse:(NSHTTPURLResponse *)response
{
    if ([response isKindOfClass:NSHTTPURLResponse.class])
    {
        // 获取cookie,并设置到本地
        NSArray * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
        for (NSHTTPCookie * cookie in cookies)
        {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            if (@available(iOS 11.0, *))
            {
                [[[WKWebsiteDataStore defaultDataStore] httpCookieStore] setCookie:cookie completionHandler:nil];
            }
        }
    }
}

static THWKWebView * PreparedWebView = nil;

+ (void)prepareWebView
{
    if (@available(iOS 9.0, *))
    {
        if (PreparedWebView != nil)
        {
            return;
        }
        if (@available(iOS 12.0, *))
        {
        }
        else
        {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                NSMutableArray * cookieList = [NSMutableArray array];
                for (NSHTTPCookie * cookie in [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies)
                {
                    if ([defaultCookieNames containsObject:cookie.name])
                    {
                        [cookieList addObject:cookie];
                    }
                }
                for (NSHTTPCookie * cookie in cookieList)
                {
                    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
                }
            });
        }
        THWKWebView * webview = [[self alloc] initCustomize];
        CGRect windowFrame = [UIApplication sharedApplication].keyWindow.bounds;
        [webview setFrame:CGRectMake(windowFrame.origin.x, windowFrame.size.height, windowFrame.size.width, windowFrame.size.height)];
        [[UIApplication sharedApplication].keyWindow insertSubview:webview atIndex:0];
        PreparedWebView = webview;
    }
}

+ (THWKWebView *)getInstance
{
    if (@available(iOS 9.0, *))
    {
        THWKWebView * tempWebView = nil;
        if (PreparedWebView != nil)
        {
            tempWebView = PreparedWebView;
            [tempWebView refreshScript];
            [PreparedWebView removeFromSuperview];
            PreparedWebView = nil;
        }
        else
        {
            tempWebView = [[self alloc] initCustomize];
        }
        [self prepareWebView];
        return tempWebView;
    }
    return nil;
}

- (void)dealloc
{
    if (self.kUserContentController)
    {
        [self.kUserContentController removeScriptMessageHandlerForName:zh_WEB_EVENT_UserControllerName];
    }
}

- (instancetype)initCustomize
{
    WKWebViewConfiguration * configuration = [WKWebViewConfiguration new];
    configuration.mediaPlaybackRequiresUserAction = NO;
    configuration.allowsInlineMediaPlayback = YES;
    configuration.processPool = [self.class sharedProcessPool];
    if (@available(iOS 9.0, *))
    {
        configuration.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
//        configuration.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
    }
    WKUserContentController * userContentController = [WKUserContentController new];
    self.kUserContentController = userContentController;
    //脚本注入
    [self refreshScript];
    //原生JS交互处理器
    id<THWKMessageHandlerProtocol> messageHandler = [THWKMessageHandlerManager shareManager].wkMsgHandleClass.class.new;
    if(messageHandler){
        [userContentController addScriptMessageHandler:messageHandler name:zh_WEB_EVENT_UserControllerName];
    }
    configuration.userContentController = userContentController;
    if (self = [super initWithFrame:CGRectZero configuration:configuration])
    {
        _injectNativeFunction = YES;
        _messageHandler = messageHandler;
        _messageHandler.webView = self;
        self.allowsBackForwardNavigationGestures = YES;
        self.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
        if (@available(iOS 11.0, *))
        {
            self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        self.UIDelegate = self;
        self.navigationDelegate = self;
    }
    return self;
}

- (void)setJsFileList:(NSArray<NSString *> *)jsFileList
{
    _jsFileList = jsFileList;
    _refreshScriptFlag = YES;
}

- (void)setCookieNameList:(NSArray<NSString *> *)cookieNameList
{
    _cookieNameList = cookieNameList;
    _refreshScriptFlag = YES;
}

- (void)refreshScript
{
    if (self.kUserContentController.userScripts.count > 0)
    {
        [self.kUserContentController removeAllUserScripts];
    }
    
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按

//    [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择

    WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [self.kUserContentController addUserScript:noneSelectScript];
    
    //JS交互脚本
//    TODO:默认js
//    NSString * handlerScriptPath = [KGetBundle(@"KBaseResource") pathForResource:@"WKMessageHandler" ofType:@"js"];
//    [self addHandlerScriptPathWithPath:handlerScriptPath];
    
    if (jsHandlerNames.count > 0)
    {
        for (NSString * handlerName in jsHandlerNames)
        {
            NSString * handlerScriptPath = [[NSBundle mainBundle] pathForResource:handlerName ofType:@"js"];
            [self addHandlerScriptPathWithPath:handlerScriptPath];
        }
    }
    if (self.jsFileList.count > 0)
    {
        for (NSString * handlerScriptPath in self.jsFileList)
        {
            [self addHandlerScriptPathWithPath:handlerScriptPath];
        }
    }
    //cookie注入脚本
    NSArray<NSString *> * cookieNameList = self.cookieNameList ?: defaultCookieNames;
    NSString * cookieScriptString = [self.class cookieScript:cookieNameList];
    if (cookieScriptString.length > 0)
    {
        WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:cookieScriptString injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [self.kUserContentController addUserScript:cookieScript];
    }
}

- (void)addHandlerScriptPathWithPath:(NSString *)handlerScriptPath
{
    if (handlerScriptPath != nil)
    {
        WKUserScript * handlerScript = [[WKUserScript alloc] initWithSource:[NSString stringWithContentsOfFile:handlerScriptPath encoding:NSUTF8StringEncoding error:nil] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [self.kUserContentController addUserScript:handlerScript];
    }
}

- (void)setWhiteClassList:(NSArray<Class> *)classList whiteObjectList:(NSArray<NSObject *> *)objectList
{
//    self.messageHandler.objectList = objectList;
//    self.messageHandler.classList = classList;
}

- (void)setInjectNativeFunction:(BOOL)injectNativeFunction
{
    _injectNativeFunction = injectNativeFunction;
//    self.messageHandler.enabled = injectNativeFunction;
}

- (void)setCustomUserAgent:(NSString *)customUserAgent
{
    if (@available(iOS 9.0, *))
    {
        [super setCustomUserAgent:customUserAgent];
    }
}

- (nullable WKNavigation *)loadRequest:(NSURLRequest *)request
{
    if (self.refreshScriptFlag || hqHandleCookieForRequest)
    {
        [self refreshScript];
        self.refreshScriptFlag = NO;
    }
    if (hqHandleCookieForRequest)
    {
        if ([[request.URL scheme] hasPrefix:@"http"])
        {
//            [self refreshScript];
            NSArray<NSHTTPCookie *> * cookieList = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
            if (cookieList.count > 0)
            {
                NSMutableURLRequest * mutableRequest = [request isKindOfClass:[NSMutableURLRequest class]] ? (NSMutableURLRequest *)request : [request mutableCopy];
                NSDictionary * cookieHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieList];
                [cookieHeader enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                    [mutableRequest setValue:obj forHTTPHeaderField:key];
                }];
                return [super loadRequest:mutableRequest];
            }
        }
    }
    return [super loadRequest:request];
}

- (void)viewWillAppear
{
    if (!self.isLoading && self.URL != nil)
    {
        [self reload];
    }
}

#pragma mark - WKUIDelegate Methods
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame] && navigationAction.request.URL != nil)
    {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

- (void)webViewDidClose:(WKWebView *)webView
{
    
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    if (message.length > 0)
    {
        [[[THAlertView alloc] initWithTitle:@"提示" desc:message sureBtnTitle:@"知道了" actionHandler:^(THAlertView * _Nonnull alertView) {
            
        }] show] ;
        return;
    }
    completionHandler();
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
{
    if (message.length > 0)
    {
        [[[THAlertView alloc] initWithTitle:@"提示" desc:message sureBtnTitle:@"确认" cancelBtnTitle:@"取消" actionHandler:^(THAlertView * _Nonnull alertView) {
            
        } cancelHandler:nil] show] ;
        return;
    }
    completionHandler(NO);
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
{
//    BOOL isHandled = NO;
//    NSString * result = [self.messageHandler handlePrompt:prompt handled:&isHandled];
//    if (isHandled)
//    {
//        completionHandler(result);
//    }
//    else
//    {
//        KUIAlertView * alertView = [KUIAlertView alertWithTitle:nil message:prompt leftBtn:@"确认" rightBtn:nil handler:nil];
//        alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
//        UITextField * textField = [alertView textFieldAtIndex:0];
//        textField.text = defaultText;
//        [alertView setHandler:^(NSInteger index) {
//            completionHandler(textField.text);
//        }];
//        if ([KWindowPriority checkPriority:alertView.windowPriority])
//        {
//            alertView.forceExcuteHandler = YES;
//            [alertView show];
//            return;
//        }
        completionHandler(@"");
//    }
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    //支持scheme跳转 、AppStore跳转
    NSURL * url = navigationAction.request.URL;
    //支持文件路径
    if (url.isFileURL)
    {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    if (![url.scheme hasPrefix:@"http"]
        || [url.host isEqualToString:@"itunes.apple.com"])
    {
        if ([url.scheme isEqualToString:@"tel"])
        {
            url = [NSURL URLWithString:[url.absoluteString stringByReplacingOccurrencesOfString:@"tel" withString:@"telprompt"]];
        }
        if ([UIApplication.sharedApplication canOpenURL:url])
        {
            decisionHandler(WKNavigationActionPolicyCancel);
            [UIApplication.sharedApplication openURL:url];
            return;
        }
    }
    //cookie校验失败则重新加载request 返回时不校验cookie，防止无限循环
    if (navigationAction.navigationType != WKNavigationTypeBackForward
        && ![self.class validateCookieForRequest:navigationAction.request])
    {
        decisionHandler(WKNavigationActionPolicyCancel);
        self.reloadAction = navigationAction;
        [webView loadRequest:navigationAction.request];
    }
    else
    {
        if ([self.reloadAction.request.URL isEqual:navigationAction.request.URL])
        {
            navigationAction = self.reloadAction;
        }
        self.reloadAction = nil;
        if ([self.delegate respondsToSelector:_cmd])
        {
            return [self.delegate webView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler];
        }
//        else if ([self.delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)])
//        {
//            BOOL allow = [(id<HZWWebViewDelegate>)self.delegate webView:(id)webView shouldStartLoadWithRequest:navigationAction.request navigationType:[[KWebInterceptor sharedInstance] typeForWkNavigationType:navigationAction.navigationType]];
//
//            decisionHandler(allow ? WKNavigationActionPolicyAllow : WKNavigationActionPolicyCancel);
//        }
        else
        {
            //必须执行decisionHandler
            decisionHandler(WKNavigationActionPolicyAllow);
        }
    }
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    [self handleCookieFromResponse:(NSHTTPURLResponse *)navigationResponse.response];
    if ([self.delegate respondsToSelector:_cmd])
    {
        [self.delegate webView:webView decidePolicyForNavigationResponse:navigationResponse decisionHandler:decisionHandler];
    }
    else
    {
        decisionHandler(WKNavigationResponsePolicyAllow);
    }
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    if ([self.delegate respondsToSelector:_cmd])
    {
        [self.delegate webView:webView didStartProvisionalNavigation:navigation];
    }
    else if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)])
    {
        [self.delegate webView:webView didStartProvisionalNavigation:navigation];
    }
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    if ([self.delegate respondsToSelector:_cmd])
    {
        [self.delegate webView:webView didReceiveServerRedirectForProvisionalNavigation:navigation];
    }
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
{
    if ([self.delegate respondsToSelector:_cmd])
    {
        [self.delegate webView:webView didFailProvisionalNavigation:navigation withError:error];
    }
    else if ([self.delegate respondsToSelector:@selector(webView:didFailLoadWithError:)])
    {
//        [(id<HZWWebViewDelegate>)self.delegate webView:(id)webView didFailLoadWithError:error];
        [self.delegate webView:webView didFailProvisionalNavigation:navigation withError:error];
    }
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation
{
    if ([self.delegate respondsToSelector:_cmd])
    {
        [self.delegate webView:webView didCommitNavigation:navigation];
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    if ([self.delegate respondsToSelector:_cmd])
    {
        [self.delegate webView:webView didFinishNavigation:navigation];
    }
    else if ([self.delegate respondsToSelector:@selector(webViewDidFinishLoad:)])
    {
//        [(id<HZWWebViewDelegate>)self.delegate webViewDidFinishLoad:(id)webView];
        [self.delegate webView:webView didFinishNavigation:navigation];
    }
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    if ([self.delegate respondsToSelector:_cmd])
    {
        [self.delegate webView:webView didFailNavigation:navigation withError:error];
    }
    else if ([self.delegate respondsToSelector:@selector(webView:didFailLoadWithError:)])
    {
//        [(id<HZWWebViewDelegate>)self.delegate webView:(id)webView didFailLoadWithError:error];
        [self.delegate webView:webView didFailNavigation:navigation withError:error];
    }
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
    if ([self.delegate respondsToSelector:_cmd])
    {
        [self.delegate webView:webView didReceiveAuthenticationChallenge:challenge completionHandler:completionHandler];
    }
    else
    {
//        TODO:
//        NSURLCredential * credential = [KSSLPinning credentialForChallenge:challenge pinMode:KSSLPinningModeNone validateDomain:YES allowsInvalideCertificates:NO];
//        if (credential != nil)
//        {
//            completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
//        }
//        else
        {
            completionHandler(NSURLSessionAuthChallengePerformDefaultHandling,nil);
        }
    }
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
    if ([self.delegate respondsToSelector:_cmd])
    {
        if (@available(iOS 9.0, *))
        {
            [self.delegate webViewWebContentProcessDidTerminate:webView];
        }
    }
    else
    {
        [webView reload];
    }
}

- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL
{
    if (@available(iOS 9.0, *))
    {
        [self loadData:data MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:baseURL];
    }
}

- (WKNavigation *)reload
{
    //兼容下拉刷新返回效果
    if (self.scrollView.contentInset.top > 0 && self.scrollView.contentOffset.y < 0)
    {
        [self loadRequest:self.request];
        return nil;
    }
    [self refreshScript];
    return [super reload];
}

+ (void)cleanCache:(NSSet *)dataTypes complete:(dispatch_block_t)complete
{
    if (@available(iOS 9.0, *))
    {
        dataTypes = dataTypes.count > 0 ? dataTypes : [WKWebsiteDataStore allWebsiteDataTypes];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:dataTypes modifiedSince:[NSDate dateWithTimeIntervalSince1970:0] completionHandler:^{
            KExecuteBlock(complete);
        }];
    }
}
///防止9.3.5崩溃
- (void)willMoveToSuperview:(UIView *)newSuperview
{
    if (newSuperview == nil)
    {
        self.scrollView.delegate = nil;
    }
}

+ (THWKWebView *)getPrepareWebView
{
    return PreparedWebView;
}

@end
